﻿using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using ECRMS.Biz.Dom;
using ECRMS.Data;

namespace ECRMS.Biz
{
    public class EcIndexLogic
    {
        public List<EcIndex> GetEcIndexes(Guid parentIndexRefId)
        {
            using (var dataContext = ECRMSDataContext.NewInstance())
            {
                return (from idx in dataContext.GetTable<ECIndex>()
                        where idx.ParentIndexRefId == parentIndexRefId
                        select new EcIndex
                        {
                            IndexRefId = idx.IndexRefId,
                            ParentIndexRefId = idx.ParentIndexRefId,
                            Description = idx.Description,
                            Note = idx.Note,
                            InputTypeId = idx.InputTypeId,
                            Percentage = idx.Percentage
                        }).ToList();
            }
        }

        public void SaveEcIndex(EcIndex idx)
        {
            using (var dataContext = ECRMSDataContext.NewInstance())
            {
                ECIndex dbIdx = null;

                if (idx.IndexRefId != Guid.Empty)
                {
                    dbIdx = dataContext.GetTable<ECIndex>()
                            .FirstOrDefault(q => q.IndexRefId == idx.IndexRefId);
                }
                else
                    idx.IndexRefId = Guid.NewGuid();

                if (dbIdx == null)
                {
                    dbIdx = new ECIndex
                    {
                        IndexRefId = idx.IndexRefId,
                        CreateDate = DateTime.Now,
                        IsDisabled = false
                    };
                    dataContext.GetTable<ECIndex>().InsertOnSubmit(dbIdx);
                }

                dbIdx.Description = idx.Description;
                dbIdx.Note = idx.Note;
                dbIdx.InputTypeId = idx.InputTypeId;
                dbIdx.Percentage = idx.Percentage;
                dbIdx.ParentIndexRefId = idx.ParentIndexRefId;

                dataContext.SubmitChanges();
            }
        }

        public List<EcIndexGroup> GetEcIndexGroups()
        {
            using (var dataContext = ECRMSDataContext.NewInstance())
            {
                return (from idxGroup in dataContext.GetTable<ECIndexGroup>()
                        select new EcIndexGroup
                        {
                            IndexGroupRefId = idxGroup.IndexGroupRefId,
                            Name = idxGroup.Name,
                            TradeId = idxGroup.TradeId,
                            CreateDate = idxGroup.CreateDate
                        }).ToList();
            }
        }
    }
}
